#include "PlayWidget.h"
#include "ui_PlayWidget.h"

#include <QApplication>
#include <QScreen>
#include <QRect>
#include <QKeyEvent>
#include <QFont>
#include <iostream>

PlayWidget::PlayWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlayWidget),
    mpvProcess(new QProcess())
{
    ui->setupUi(this);
    showVideo_flag = false;
    showLabel_flag = true;
    taskEnd_flag == false;
    playMode = -1;
    trainVideoNum = 0;
    predictVideoNum = 0;
    video_index = 0;
    videoPlaying = false;

    
    // 绑定到某一个窗口
    processArg << "--wid=" + QString::number((qulonglong)this->winId());
    // // 全屏播放
    // ProcessArg << "--fs";

    // 获取主屏幕的信息
    QScreen *screen = QApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();

    // 计算窗口的位置和大小，使其充满屏幕右边
    int windowWidth = screenGeometry.width() / 2; // 窗口宽度为屏幕宽度的一半
    int windowHeight = screenGeometry.height(); // 窗口高度为屏幕高度
    int windowX = screenGeometry.width() - windowWidth; // 窗口的X位置（右半部分）
    int windowY = 0; // 窗口的Y位置（顶部）

    // 设置窗口的位置和大小
    // this->setWindowFlags(Qt::FramelessWindowHint); // 隐藏顶部状态栏
    this->setGeometry(windowX, windowY, windowWidth, windowHeight);

    ui->label->setFont(QFont("videoPlayer", 36));

    connect(mpvProcess, SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(video_shutDown(int,QProcess::ExitStatus)));

    // 显示窗口
    this->show();
}

PlayWidget::~PlayWidget()
{
    // if(mpvProcess->state() == QProcess::Running){
    //     mpvProcess->kill();
    // }
    delete mpvProcess;
    delete ui;
}



/**********************************
 * 函数名：setWords
 * 功能：视频播放窗口显示文字
 * 输入：无
 * 输出：无
 * 备注：无
**********************************/
void PlayWidget::showWords(const QString &text){
    // QFont font = ui->label->font();  // 获取当前字体
    // font.setBold(true);              // 设置字体为加粗
    // ui->label->setFont(font);        // 应用修改后的字体
    ui->label->setFont(QFont(ui->label->font().family(), ui->label->font().pointSize(), QFont::Bold));
    ui->label->setText(text);
    ui->label->show();
}
void PlayWidget::hideWords(){
    ui->label->hide();
}


void PlayWidget::setVideoList(QStringList &fileNames){
    trainVideoNum = fileNames.size();
    std::cout << "num:" << trainVideoNum << std::endl;
    for(auto &it : fileNames){
        videoList.append(it);
        labelList.append(getLabelFromFile(it));
    }
}

void PlayWidget::set_Video_flag(bool flag){
    showVideo_flag = flag;
}

/**********************************
 * 函数名：set_play_mode
 * 功能：
 * 输入：mode:0:训练；1:预测
 * 输出：无
 * 备注：无
**********************************/
void PlayWidget::set_play_mode(int mode){
    playMode = mode;
}

EmotionInterface::EmoMode PlayWidget::getLabelFromFile(QString &fileName){
    // 文件名的第一个数字就是标签
    int lastSlashIndex = fileName.lastIndexOf('/');
    int label;
    if (lastSlashIndex != -1 && lastSlashIndex + 1 < fileName.length()) {
        // 获取 '/' 后的第一个字符
        label = fileName.at(lastSlashIndex + 1).digitValue();
        // std::cout << "label: " << label << std::endl;
    } else {
        std::cerr << "label not found!" << std::endl;
    }

    switch (label)
    {
        // 消极
    case 1:
        return EmotionInterface::EmoMode::Negative;
        break;
        // 中性
    case 2:
        return EmotionInterface::EmoMode::Neutral;
        break;
        // 积极
    case 3:
        return EmotionInterface::EmoMode::Positive;
        break;
    default:
        return EmotionInterface::EmoMode::Free;
        break;
    }
    
}

/**********************************
 * 函数名：work
 * 功能：播放视频，发送视频标签
 * 输入：无
 * 输出：无
 * 备注：无
**********************************/
void PlayWidget::work(){
    if(showVideo_flag){
        // ui->label->hide();
        if(videoPlaying){
            return ;
        }
        if(video_index >= trainVideoNum){
            showVideo_flag = false;
            showLabel_flag = true;
            taskEnd_flag = true;
            video_index = 0;
            videoList.clear();
            labelList.clear();
            showWords("任务结束");
            emit videoPlayer_shutDown();
            // emit sendDataLabel(EmotionInterface::EmoMode::Free);
            return;
        }

        // 播放器参数
        QStringList arguments(processArg);
        arguments << videoList[video_index];
        // qDebug() << arguments;
        mpvProcess->start("mpv", arguments);
        videoPlaying = true;

        emit sendVideoLabel(labelList[video_index]);

        // 训练模式输出数据标签和视频标签
        if(playMode == 0){
            emit sendDataLabel(labelList[video_index], playMode, true); 
        }
        
        else if (playMode == 1){
            emit sendDataLabel(labelList[video_index], playMode, true); 
        }
        
    }
    else if(showLabel_flag){
        ui->label->show();
    }
}

void PlayWidget::video_shutDown(int exitCode, QProcess::ExitStatus exitStatus){
    if(exitStatus == QProcess::CrashExit){
        // 进程被强制终止
        emit sendDataLabel(labelList[video_index], playMode, false);
        return;
    }

    emit sendDataLabel(labelList[video_index], playMode, false);
    // 视频播放完后休息20s
    showWords("休息20s\n再开始下一个任务吧~");
    QEventLoop loop;//定义一个新的事件循环
    QTimer::singleShot(20000, &loop, SLOT(quit()));//创建单次定时器，槽函数为事件循环的退出函数
    loop.exec();//事件循环开始执行，程序会卡在这里，直到定时时间到，本循环被退出
    videoPlaying = false;
    ++video_index;
}

void PlayWidget::playVideoFromFile(QString filePath){
    QStringList arguments(processArg);
    arguments << filePath;
    mpvProcess->start("mpv", arguments);
    emit sendVideoLabel(EmotionInterface::EmoMode::Positive);
}

void PlayWidget::keyPressEvent(QKeyEvent *event){
    if (event->key() == Qt::Key_Escape) {
        showNormal();
    }
}

void PlayWidget::mouseDoubleClickEvent(QMouseEvent *event){
    if (event->button() == Qt::LeftButton) {
        if (isFullScreen()) {
            showNormal();
        } else {
            showFullScreen();
        }
    }
}

